package translation;

import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * Created by xwj on 2017/12/3.
 */
public class LightFieldOrder {


    final static String path = "J:\\视频文件\\光场\\train\\"; // yuv路径
    final static String outputpath = "J:\\视频文件\\光场\\"; // outyuv路径
    final static int width=624;
    final static int height=432;
    final static int frameNum=121;


    public static File[] getFileNames() {
        File f = new File(path);
        if (!f.exists()) {
            System.out.println(path + " not exists");
            return null;
        }

        File listFiles[] = f.listFiles();
        return listFiles;
    }

    public static double calculateEntropy(byte[] bytes){
        int len=bytes.length;
        int[] countY=new int[1024];
        double entropy=0.0;
        int Ysize=width*height;
        for(int i=0;i<Ysize*2;i+=2){
            try {
                int num=(bytes[i]&0xFF)+(bytes[i+1]&0xFF)*256;
                countY[num]++;
            }catch (Exception e){
                e.printStackTrace();
                System.out.println(bytes[i]+bytes[i+1]*256);
            }

        }
        for(int i=0;i<1024;i++){
            if(countY[i]>0) {
                double rate=(countY[i]+0.0) / Ysize;
                double lograte=Math.log(rate);
                entropy -=  rate*lograte ;
            }
        }
        return entropy;
    }

    public static void main(String[] args){
        File[] listFiles=getFileNames();
        int yuvsize=width*height*2;//422格式 注意是10bit
        for(File yuv:listFiles) {
            if(!yuv.getName().endsWith(".yuv")) continue;
            System.out.println("开始读取" + yuv.getName());
            FileInputStream inputStream = null;
            FileOutputStream outputStream=null;
            try {
                inputStream = new FileInputStream(yuv);
                TreeMap<Double,Integer> entropyMap=new TreeMap();
                byte[][] bytes=new byte[frameNum][yuvsize*2];//10bit
                for(int i=0;i<frameNum;i++){
                    int num=inputStream.read(bytes[i]);
                    double entropy=calculateEntropy(bytes[i]);
                    //System.out.println(i+"  "+entropy);
                    entropyMap.put(entropy,i);
                }

                String outputFile=outputpath+"last-"+yuv.getName();
                outputStream = new FileOutputStream(new File(outputFile));
                while(entropyMap.size()>0){
                    int num=entropyMap.pollLastEntry().getValue();
                    outputStream.write(bytes[num]);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }


        }


    }


}
